/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javanetworking;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Admin
 */
public class Server implements Runnable {

    DatagramSocket socket = null;

    public Server(DatagramSocket socket_) {
        this.socket = socket_;
    }

    @Override
    public void run() {
        while (true) {
            byte[] buff = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buff, buff.length);
            try {
                System.out.println("Listerning");
                socket.receive(packet);
                System.out.println("Data: " + new String(packet.getData()));
                 new Thread(new Responder(socket, packet)).start();
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String[] args) throws SocketException, IOException, InterruptedException, Exception {
        List<host> lstHost = new ArrayList<>();
        File fi_nodes = new File("nodes.map");
        BufferedReader br = new BufferedReader(new FileReader(fi_nodes));
        int nhost = Integer.parseInt(br.readLine());
        for (int i = 0; i < nhost; i++) {
            String[] s = br.readLine().split(" ");
            host h = new host();
            h.setId(Integer.parseInt(s[0]));
            h.setIp(s[1]);
            h.setPort(Integer.parseInt(s[2]));
            lstHost.add(h);
        }
        lstHost.get(1);


        DatagramSocket socket = new DatagramSocket(9999);
        String input;
        Server server = new Server(socket);
        Thread t = new Thread(server);
        t.start();

//        System.out.println("Input data:");
//        DataInputStream dis = new DataInputStream((System.in));
//        input = dis.readLine();
        for (int i = 0; i < lstHost.size(); i++) {
            
            host e=lstHost.get(i);
            new Thread(new Send(socket,e.getIp(),e.getPort(), "May Tao".getBytes())).start();
            
        }
        //} while ("1".compareToIgnoreCase(input) == 0);

    }
}
